<template>
  <div class="pane-account">
    <el-form ref="accountFormRef" :model="accountForm" :rules="accountRules" label-width="60px">
      <el-form-item label="账号" prop="account">
        <el-input v-model="accountForm.account" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="accountForm.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
// const emits = defineEmits(['accountInfo'])
import { ref, reactive, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import useLoginStore from '@/store/login/login'
import type { Icount } from '@/types'
import { localCache } from '@/utils/cache'
import { log } from 'util'

const loginStore = useLoginStore()

const CACHE_NAME = 'account'
const CACHE_PASSWORD = 'password'

const accountFormRef = ref<FormInstance>()
const accountForm = ref<Icount>({
  account: localCache.getCache(CACHE_NAME) ?? '',
  password: localCache.getCache(CACHE_PASSWORD) ?? '',
})
const accountRules = reactive<FormRules<Icount>>({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{6,20}$/, message: '必须是6~20位数字或字母组合', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{3,}$/, message: '必须是3位以上数字或字母组合', trigger: 'blur' },
  ],
})

// 登录方式一：代码写在子组件中，将方法暴露给父组件，父组件点击登录按钮的时候调子组件的登录方法
async function loginAction(isRememberPass: boolean) {
  await accountFormRef.value?.validate((valid, fields) => {
    if (valid) {
      // 执行登录
      loginStore.loginAccountAction(accountForm.value)
      // 记住密码--可以在loginAccountAction的then函数中保存密码，更严谨
      if (isRememberPass) {
        localCache.setCache(CACHE_NAME, accountForm.value.account)
        localCache.setCache(CACHE_PASSWORD, accountForm.value.password)
      } else {
        localCache.removeCache(CACHE_NAME)
        localCache.removeCache(CACHE_PASSWORD)
      }
    } else {
      ElMessage.error('请按要求输入账号密码，之后再重试~')
    }
  })
}
// 将方法暴露出去
defineExpose({
  loginAction,
})

// 登录方式二：监听表单变化，将表单数据传给父组件，在父组件中执行登录逻辑
// watch(
//   () => accountForm.value,
//   (newVal) => {
//     console.log('表单最新的值', newVal)
//     emits('accountInfo', newVal)
//   },
//   {
//     deep: true,
//   },
// )
</script>

<style scoped lang="less">
.pane-account {
  color: red;
}
</style>
